<template>
  <div v-if="product">
    {{product.id}}
    <img :src="product.pro_img" alt="">
    商品名称：{{product.pro_name}}
    商品价格：{{product.pro_price}}
    库存：{{product.stocks}}
    <button @click="AddCart()">添加到购物车</button>
    <button @click="gocart()">去购物车</button>
  </div>
</template>

<script>
export default {
    data(){
        return{
            id:parseInt(this.$route.params.id),
            product:null
        }
    },
    methods: {
            getProduct(){
                setTimeout( () => {
                    //模拟ajax获取具体商品数据
                    this.product = this.$store.state.productList.find(item => item.id === this.id);
                }, 300);
            },
            AddCart(){
                //增加1件此商品至购物车，返回一个Promise
                this.$store.dispatch('add', this.id).then(text=>{
                    console.log(text)
                },error=>{
                    window.alert(error)
                })
            },
            gocart(){
                this.$router.push({path:'/cart'})
            }
    },
    mounted(){
        this.getProduct();
    }
}
</script>

<style>

</style>